package cn.itwen.star.graph.core.service.impl;

import cn.itwen.star.graph.comfyui.client.pojo.ComfyuiTask;
import cn.itwen.star.graph.core.service.RedisService;
import cn.itwen.star.graph.core.service.WsNoticeService;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WsNoticeServiceImpl implements WsNoticeService {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private RedisService redisService;

    public final static String COMFYUI_QUEUE_TOPIC = "/topic/messages";

    /**
     * 给某个用户发送消息
     * @param wsClientId
     * @param message
     */
    @Override
    public void sendToUser(String wsClientId, String message) {
        simpMessagingTemplate.convertAndSendToUser(wsClientId, COMFYUI_QUEUE_TOPIC, message);
    }

    /**
     * 给所有用户发送消息
     * @param message
     */
    @Override
    public void sendToAll(String message) {
        simpMessagingTemplate.convertAndSend(COMFYUI_QUEUE_TOPIC, message);
    }

    /**
     * 给某个用户发送错误消息
     * @param promptId
     * @param data
     */
    @Override
    public void sendError(String promptId, HashMap<String, Object> data) {
        ComfyuiTask task = redisService.getStartedTask(promptId);
        if (task != null){
            data.put("type","execution_error");
            sendToUser(task.getWsClientId(), JSON.toJSONString(data));
        }
    }
}
